<template>
  <div>
    <selectWithoutHttp
      :ref="`linkFormRef${selectWidget?selectWidget.key:''}`"
      v-model="selectWidget.options.remoteParams"
      :list-data="linkFormList"
      :item-max-width="240"
      value-type="object"
      filterable
      placeholder="请选择表单"
      label-name="name"
      key-name="id"
      class="width240 mb"
      @change="handelChangeForm" />
    <selectWithoutHttp
      :ref="`linkKeyRef${selectWidget?selectWidget.key:''}`"
      v-model="selectWidget.subform"
      :list-data="linkFormKeyList"
      :item-max-width="240"
      value-type="object"
      multiple
      collapse-tags
      clearable
      filterable
      placeholder="请选择字段"
      label-name="name"
      key-name="key"
      class="width240"
      @change="subformChange" />
  </div>
</template>

<script>
import { getLinkForm, getLinkFormKey } from '@/api/process';
import selectWithoutHttp from '@/components/Common/selectWithoutHttp';
import { EventBus } from '@/utils/eventBus';
import { setLinkStatistics } from '@/views/legal/process/mixins/linkFormUtils.js';
import { formulaChange } from '@/views/legal/process/components/formMake/utils/index.js';

export default {
  components: { selectWithoutHttp },
  model: {
    prop: 'selectWidget',
    event: 'changeData'
  },
  props: {
    selectWidget: {
      type: Object,
      default: () => ({})
    },
    widgetData: {
      type: Object,
      default: () => {
        return {
          list: [],
          config: {
            labelWidth: 100, labelPosition: 'right',
            keyToFormula: {} // 公式字段的映射表（被引用的字段: 引用它的公式字段）
          }
        };
      }
    }
  },
  data() {
    return {
      linkFormList: [],
      linkFormKeyList: []
    };
  },
  watch: {
    selectWidget: {
      handler(newVal) {
        this.$emit('statusCheck');
        if (this.selectWidget && this.selectWidget.options.remoteParams.id) {
          const moduleId = this.selectWidget.options.remoteParams.workFlowId;
          this.getKey(moduleId);
        } else {
          if (this.selectWidget) this.linkFormKeyList = [];
        }
      },
      immediate: true
    },
    'selectWidget.subform': {
      handler(newVal, oldVal) {
        if (newVal.length < oldVal.length) {
          const newKeys = newVal.map(i => i.key);
          const removeField = oldVal.filter(i => {
            return !newKeys.includes(i.key);
          });
          if (removeField && removeField.length) {
            removeField.forEach(j => {
              formulaChange('remove', this.widgetData, this.selectWidget, `linkForm*${this.selectWidget.key}*${j.key}`);
            });
          }
        }
      }
    }
  },
  created() {
    this.getForm();
  },
  methods: {
    getForm() {
      getLinkForm().then(res => {
        if (res.code === 200) {
          // const selfId = this.$route.params.id;
          // if (selfId) {
          //   res.data = res.data.filter(i => {
          //     return Number(i.id) !== Number(selfId);
          //   });
          // }
          if (this.selectWidget.options.remoteParams) {
            const hasData = res.data.find(i => i.id === this.selectWidget.options.remoteParams.id);
            if (!hasData) {
              this.$set(this.selectWidget, 'subform', []);
              this.$set(this.selectWidget.options, 'remoteParams', { id: '' });
            }
          }
          this.linkFormList = res.data;
        }
      });
    },
    getKey(id) {
      getLinkFormKey({ id }).then((res) => {
        if (res.code === 200) {
          const notShow = ['grid', 'titleExplain', 'linkForm', 'subform', 'title'];
          const keys = [];
          res.data = res.data.filter(i => {
            i.key = i.key ? i.key : i.id;
            keys.push(i.key);
            i.linkFormKey = this.selectWidget.key;
            i.isLinkField = true;
            const isSecret = i.options && i.options.isSecret;
            return i.name && (!i.type || !notShow.includes(i.type)) && !isSecret;
          });
          if (this.selectWidget.subform) {
            this.selectWidget.subform = this.selectWidget.subform.filter(i => {
              return keys.includes(i.key);
            });
          }
          this.linkFormKeyList = res.data;
        }
      });
    },
    subformChange(data) {
      EventBus.$emit('changeLinkForm', this.selectWidget);
      setLinkStatistics(this.selectWidget);
      this.$emit('statusCheck');
    },
    handelChangeForm(data) {
      this.linkFormKeyList = [];
      this.$set(this.selectWidget, 'subform', []);
      this.getKey(data.workFlowId);
      this.subformChange([]);
      this.$emit('statusCheck');
      this.$set(this.selectWidget.options, 'presetFilter', {});
      this.$set(this.selectWidget.options, 'presetFilterParams', '');
      this.$set(this.selectWidget.options, 'isFillPreset', false);
    }
  }
};
</script>

<style lang="scss" scoped>
.mb {
  margin-bottom: 10px;
}
.width240 {
  width: 240px;
  &::v-deep {
    .el-input__inner {
      width: 240px;
    }
  }
}
</style>
